package pipeline

import (
	"encoding/binary"
	"io"
	"sort"
)

func ArraySource(a ...int) chan int {
	out := make(chan int)
	go func() {
		for _, v := range a {
			out <- v
		}
		close(out)
	}()
	return out
}

func InMemSOrt(in <-chan int) <-chan int {
	out := make(chan int)

	go func() {
		a := []int{}
		for v := range in {
			a = append(a, v)
		}
		sort.Ints(a)

		for _, v := range a {
			out <- v
		}
		close(out)
	}()

	return out
}

func Merge(n1, n2 <-chan int) <-chan int {
	out := make(chan int)
	go func() {
		v1, ok1 := <-n1
		v2, ok2 := <-n2

		for ok1 || ok2 {
			if !ok2 || (ok1 && v1 <= v2) {
				out <- v1
				v1, ok1 = <-n1
			} else {
				out <- v2
				v2, ok2 = <-n2
			}

		}
		close(out)
	}()

	return out
}

func ReaderSOurce(reader io.Reader) <-chan int {

	out := make(chan int)

	go func() {
		buffer := make([]byte, 8)

		for {
			n, err := reader.Read(buffer)

			if n > 0 {
				v := int(binary.BigEndian.Uint64(buffer))
				out <- v
			}

			if err != nil {
				break
			}

		}
		close(out)
	}()
	return out
}
